package com.harveyguo.nihonngo.handler;

import cn.dev33.satoken.exception.SaTokenException;
import com.harveyguo.nihonngo.exception.BizException;
import com.harveyguo.nihonngo.exception.ErrorResponse;
import com.harveyguo.nihonngo.exception.ExceptionType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author：HarveyGuo
 * @Package：com.harveyguo.nihonngo.handler
 * @Project：BestReading_back
 * @name：GlobalExceptionHandler
 * @Date：2023/2/16 17:19
 * @Filename：GlobalExceptionHandler
 * @Describe：Do something
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    public ErrorResponse bizExceptionHandler (BizException bizException) {
            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.setCode(bizException.getCode());
            errorResponse.setTrace(bizException.getStackTrace());
            errorResponse.setMessage(bizException.getMessage());
        return errorResponse;
    }


    @ExceptionHandler(value = SaTokenException.class)
    public ErrorResponse tokenExceptionHandler(SaTokenException e) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setCode(e.getCode());
//        errorResponse.setTrace(e.getStackTrace());
        errorResponse.setMessage(e.getMessage());
        return errorResponse;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse argumentExceptionHandler(MethodArgumentNotValidException exception) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setCode(ExceptionType.BAD_REQUEST.getCode());
        errorResponse.setTrace(exception.getStackTrace());
        errorResponse.setMessage(exception.getMessage());
        return errorResponse;
    }
}
